package com.lancea12.buster.android;

import java.net.Socket;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

public class RobotActivity extends Activity {


	private RobotMessageHandler arduinoHandler;
	private MediaRecorder rec;
	private Socket sock;
	private TextView temp;
	private Handler textHandler;
	private UsbManager mUsbManager;

	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.remote);

        
    	textHandler = new Handler(){
    		public void handleMessage(Message msg) {
    			String text = msg.getData().getString("response");

				temp.setText(text);
				Log.d("Buster", text);
    		};
    	};

    	
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        PendingIntent tempPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
				RobotMessageHandler.ACTION_USB_PERMISSION), 0);

		arduinoHandler = new RobotMessageHandler(mUsbManager, tempPermissionIntent);
		if(arduinoHandler.startComms()){
			new Thread(new RobotServerRunnable(textHandler, arduinoHandler)).start();
		}
		
		IntentFilter filter = new IntentFilter(RobotMessageHandler.ACTION_USB_PERMISSION);
		filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
		registerReceiver(arduinoHandler.getUsbReceiver(), filter);

		if (getLastNonConfigurationInstance() != null) {
			UsbAccessory tempAccessory = (UsbAccessory) getLastNonConfigurationInstance();
			if(arduinoHandler.openAccessory(tempAccessory)){
				new Thread(new RobotServerRunnable(textHandler, arduinoHandler)).start();
			}
		}

        temp = (TextView)findViewById(R.id.checkedTextView1);
        
        /*rec = new MediaRecorder();
        rec.setVideoSource(VideoSource.CAMERA);
        
        ParcelFileDescriptor pdf = ParcelFileDescriptor.fromSocket(sock);
        rec.setOutputFile(pdf.getFileDescriptor());
        */
	}
	
	@Override
	public Object onRetainNonConfigurationInstance() {
		if (arduinoHandler.getAccessory() != null) {
			return arduinoHandler.getAccessory();
		} else {
			return super.onRetainNonConfigurationInstance();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	
	@Override
	public void onPause() {
		super.onPause();
		arduinoHandler.closeAccessory();
	}

	@Override
	public void onDestroy() {
		unregisterReceiver(arduinoHandler.getUsbReceiver());
		super.onDestroy();
	}




}
